package com.ingenio.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;

import com.ingenio.business.Categoria;
import com.ingenio.business.Rubro;
import com.ingenio.dao.CategoriaAdapter;
import com.ingenio.dao.RubroAdapter;

/**
 * Servlet implementation class DevolverPrecioServlet
 */
@WebServlet("/DevolverRubros")
public class DevolverRubrosCategoriaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DevolverRubrosCategoriaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Integer idCategoria = Integer.parseInt(request.getParameter("idCategoria"));
		CategoriaAdapter ca = new CategoriaAdapter();
		RubroAdapter ra = new RubroAdapter();
		JSONObject json = new JSONObject();
		try {
			Categoria c = ca.devolverCategoria(idCategoria);
			if (c != null){
				JSONArray jaRub = new JSONArray();
				List<Rubro> rubros = ra.devolverRubrosCategoria(c);
				for (Rubro r: rubros){
					JSONObject jRubros = new JSONObject();
					jRubros.put("id", r.getIdRubro());
					jRubros.put("desc", r.getDescRubro());
					jaRub.put(jRubros);
				}
				json.put("rubros", jaRub);
			}else{
				json.put("error",true);
			}
			response.setContentType("application/json");
			response.getWriter().write(json.toString());	
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
